<template>
  <el-dialog
    v-model="visible"
    :title="activityTitle ? `报名参加 - ${activityTitle}` : '活动报名'"
    :before-close="handleClose"
    width="600px"
    :fullscreen="fullscreen"
  >
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="80px">
      <el-form-item label="选择活动" prop="activityId">
        <el-select
          v-model="formData.activityId"
          placeholder="请选择要报名的活动"
          style="width: 100%"
          filterable
          :loading="activitiesLoading"
          @focus="loadActivities"
        >
          <el-option
            v-for="activity in activitiesList"
            :key="activity.id"
            :label="activity.title"
            :value="activity.id"
          >
            <!-- <div class="activity-option">
              <div class="activity-title">{{ activity.title }}</div>
              <div class="activity-info">
                <span v-if="activity.startTime" class="activity-time">{{
                  formatDateTime(activity.startTime)
                }}</span>
                <span v-if="activity.location" class="activity-location">{{
                  activity.location
                }}</span>
              </div>
            </div> -->
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="姓名" prop="name">
        <el-input v-model="formData.name" placeholder="请输入您的姓名" />
      </el-form-item>

      <el-form-item label="手机号" prop="phone">
        <el-input v-model="formData.phone" placeholder="请输入手机号" />
      </el-form-item>

      <el-form-item label="邮箱" prop="email">
        <el-input v-model="formData.email" placeholder="请输入邮箱地址" />
      </el-form-item>

      <el-form-item label="公司名称" prop="company">
        <el-input v-model="formData.company" placeholder="请输入公司名称" />
      </el-form-item>

      <el-form-item label="职位" prop="position">
        <el-input v-model="formData.position" placeholder="请输入您的职位" />
      </el-form-item>

      <el-form-item label="特殊需求" prop="specialRequirements">
        <el-input
          v-model="formData.specialRequirements"
          type="textarea"
          :rows="3"
          placeholder="如有特殊需求请在此说明（如：素食餐、轮椅通道、同声传译等）"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" :loading="loading" @click="handleSubmit">
          提交报名
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import { ref, reactive, watch, computed, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { activityApi } from "@/api/user";

export default {
  name: "ActivityRegistrationDialog",
  props: {
    modelValue: {
      type: Boolean,
      default: false,
    },
    activityId: {
      type: [Number, String],
      default: null,
    },
    activityTitle: {
      type: String,
      default: "",
    },
    activityPlatType: {
      type: String,
      default: "",
    },
  },
  computed: {
    fullscreen() {
      return window.innerWidth <= 768;
    },
  },
  emits: ["update:modelValue", "success"],
  setup(props, { emit }) {
    const visible = ref(false);
    const loading = ref(false);
    const formRef = ref();
    const activitiesLoading = ref(false);
    const activitiesList = ref([]);
    const activityTypes = ref([]);

    const formData = reactive({
      activityId: null,
      name: "",
      phone: "",
      email: "",
      company: "",
      position: "",
      specialRequirements: "",
    });

    // 计算当前活动ID
    const currentActivityId = computed(() => {
      return formData.activityId;
    });

    const rules = {
      activityId: [
        { required: true, message: "请选择要报名的活动", trigger: "change" },
      ],
      name: [
        { required: true, message: "请输入姓名", trigger: "blur" },
        {
          min: 2,
          max: 50,
          message: "姓名长度在 2 到 50 个字符",
          trigger: "blur",
        },
      ],
      phone: [
        { required: true, message: "请输入手机号", trigger: "blur" },
        {
          pattern: /^1[3-9]\d{9}$/,
          message: "请输入正确的手机号",
          trigger: "blur",
        },
      ],
      email: [
        { type: "email", message: "请输入正确的邮箱地址", trigger: "blur" },
      ],
      company: [
        { max: 100, message: "公司名称不能超过100个字符", trigger: "blur" },
      ],
      position: [{ max: 50, message: "职位不能超过50个字符", trigger: "blur" }],
      specialRequirements: [
        { max: 500, message: "特殊需求不能超过500个字符", trigger: "blur" },
      ],
    };

    // 监听modelValue变化
    watch(
      () => props.modelValue,
      (newVal) => {
        visible.value = newVal;
        if (newVal) {
          resetForm();
          // 如果没有指定activityId，则加载活动列表
          // if (!props.activityId) {
          loadActivities();
          // }
        }
      }
    );

    // 监听visible变化
    watch(visible, (newVal) => {
      emit("update:modelValue", newVal);
    });

    // 加载活动列表
    const loadActivities = async () => {
      // if (activitiesList.value.length > 0) return; // 已经加载过了

      try {
        activitiesLoading.value = true;
        const response = await activityApi.getActivityList({
          status: "published", // 只获取已发布的活动
          activityPlatType: props.activityPlatType,
          limit: 1000, // 限制数量
        });

        console.log("活动列表API响应:", response);

        if (
          response &&
          (response.code === "200" || response.code === 200) &&
          Array.isArray(response.data)
        ) {
          activitiesList.value = response.data.filter(
            (activity) =>
              activity.status === "published" || activity.status === "ongoing"
          );
          console.log(
            "成功加载活动列表:",
            activitiesList.value.length,
            "个活动"
          );
        } else {
          console.log("活动列表数据格式不正确:", response);
          activitiesList.value = [];
        }
      } catch (error) {
        console.error("加载活动列表失败:", error);
        ElMessage.error("加载活动列表失败: " + error.message);
        activitiesList.value = [];
      } finally {
        activitiesLoading.value = false;
      }
    };

    // 格式化日期时间
    const formatDateTime = (dateTime) => {
      if (!dateTime) return "";
      const date = new Date(dateTime);
      return date.toLocaleString("zh-CN", {
        year: "numeric",
        month: "2-digit",
        day: "2-digit",
        hour: "2-digit",
        minute: "2-digit",
      });
    };

    // 重置表单
    const resetForm = () => {
      Object.assign(formData, {
        activityId: null,
        name: "",
        phone: "",
        email: "",
        company: "",
        position: "",
        specialRequirements: "",
      });
      if (formRef.value) {
        formRef.value.clearValidate();
      }
    };

    // 关闭对话框
    const handleClose = () => {
      visible.value = false;
    };

    // 提交表单
    const handleSubmit = async () => {
      if (!formRef.value) return;

      try {
        const valid = await formRef.value.validate();
        if (!valid) return;

        loading.value = true;

        const response = await activityApi.registerActivity(
          currentActivityId.value,
          {
            name: formData.name,
            phone: formData.phone,
            email: formData.email,
            company: formData.company,
            position: formData.position,
            specialRequirements: formData.specialRequirements,
            activityPlatType: props.activityPlatType,
          }
        );

        if (response.code === "200") {
          ElMessage.success("报名成功！我们会尽快与您联系确认。");
          emit("success");
          handleClose();
        } else {
          ElMessage.error(response.msg || "报名失败，请重试");
        }
      } catch (error) {
        console.error("报名失败:", error);
        ElMessage.error("报名失败，请检查网络连接后重试");
      } finally {
        loading.value = false;
      }
    };

    return {
      visible,
      loading,
      formRef,
      formData,
      rules,
      activitiesLoading,
      activitiesList,
      activityTypes,
      currentActivityId,
      loadActivities,
      formatDateTime,
      handleClose,
      handleSubmit,
    };
  },
};
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-input__inner) {
  border-radius: 6px;
}

:deep(.el-textarea__inner) {
  border-radius: 6px;
}

.activity-option {
  padding: 4px 0;
}

.activity-title {
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
}

.activity-info {
  font-size: 12px;
  color: #909399;
  display: flex;
  gap: 12px;
}

.activity-time,
.activity-location {
  display: flex;
  align-items: center;
}

.activity-time::before {
  content: "🕒";
  margin-right: 4px;
}

.activity-location::before {
  content: "📍";
  margin-right: 4px;
}
</style>
